package com.bdqn.shiro.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.shiro.pojo.Role;
import com.bdqn.shiro.pojo.SysRight;
import com.bdqn.shiro.pojo.User;
import com.bdqn.shiro.service.RoleService;
import com.bdqn.shiro.service.SysRightService;
import com.bdqn.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private UserService service;
    @Resource
    private RoleService roleService;
    @Resource
    private SysRightService sysRightService;

    @GetMapping("toLogin")
    public String toLogin() {

        return "login";
    }

    @GetMapping("main")
    public String toMain() {
        return "main";
    }

    @PostMapping("doLogin")
    public String doLogin(Model model, String usrName, String usrPassword, HttpSession session) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//认证、登录
            //认证(登录)成功
            User user = (User) subject.getPrincipal();
            Role role=user.getRole();
            role.setRights(sysRightService.findRightByRoleId(user.getUsrRoleId()));
            session.setAttribute("loginUser", user);
            return "redirect:/main";//建议重定向
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("message", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("message", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("message", "认证异常，登录失败！");
            return "login";
        }
    }


}
